import socket


def do_service(new_socket_client):
    """给浏览器返回固定字符串"""
    # 接收请求数据
    request = new_socket_client.recv(1024)
    print(request)
    # 响应数据
    response = "HTTP/1.1 200 \r\n"  # 响应头并换行
    response += "\r\n"  # 分割响应头、响应体的空行
    response += "你好。浏览器"  # 响应体
    new_socket_client.send(response.encode("gbk"))
    new_socket_client.close()


def main():
    tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 让服务端重复利用资源(端口等)
    tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    tcp_socket.bind(("", 7890))
    tcp_socket.listen(128)

    while True:
        new_socket_client, client_address = tcp_socket.accept()
        do_service(new_socket_client)

    tcp_socket.close()


if __name__ == '__main__':
    main()
